﻿<!DOCTYPE html>
<!--[if IE]><![endif]-->
<html>
  
  <head>
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async="" src="https://www.googletagmanager.com/gtag/js?id=UA-39155502-5"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
  
      gtag('config', 'UA-39155502-5');
    </script>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Referenced Relationships | MongoDB.Entities </title>
    <meta name="viewport" content="width=device-width">
    <meta name="title" content="Referenced Relationships | MongoDB.Entities ">
    <meta name="generator" content="docfx 2.58.4.0">
    <meta name="description" content="A data access library for MongoDB with an elegant api, LINQ support and built-in entity relationship management.">
    <link rel="shortcut icon" href="../images/favicon.ico">
    <link rel="stylesheet" href="../styles/docfx.vendor.css">
    <link rel="stylesheet" href="../styles/docfx.css">
    <link rel="stylesheet" href="../styles/main.css">
    <meta property="docfx:navrel" content="../toc.html">
    <meta property="docfx:tocrel" content="toc.html">
    
    <meta property="docfx:rel" content="../">
    <meta property="docfx:newtab" content="true">
    <meta property="og:title" content="MongoDB.Entities">
    <meta property="og:site_name" content="MongoDB.Entities">
    <meta property="og:url" content="https://mongodb-entities.com">
    <meta property="og:description" content="A data access library for MongoDB with an elegant api, LINQ support and built-in entity relationship management,">
    <meta property="og:type" content="website">
    <meta property="og:image" content="https://mongodb-entities.com/images/social-square.png">  
  </head>
  <body data-spy="scroll" data-target="#affix" data-offset="120">
    <div id="wrapper">
      <header>
        
        <nav id="autocollapse" class="navbar navbar-inverse ng-scope" role="navigation">
          <div class="container">
            <div class="navbar-header">
              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
              </button>
              
              <a class="navbar-brand" href="../index.html">
                <img id="logo" class="svg" src="../images/icon.png" alt="">
              </a>
            </div>
            <div class="collapse navbar-collapse" id="navbar">
              <form class="navbar-form navbar-right" role="search" id="search">
                <div class="form-group">
                  <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">
                </div>
              </form>
            </div>
          </div>
        </nav>
        
        <div class="subnav navbar navbar-default">
          <div class="container hide-when-search" id="breadcrumb">
            <ul class="breadcrumb">
              <li></li>
            </ul>
          </div>
        </div>
      </header>
      <div class="container body-content">
        
        <div id="search-results">
          <div class="search-list">Search Results for <span></span></div>
          <div class="sr-items">
            <p><i class="glyphicon glyphicon-refresh index-loading"></i></p>
          </div>
          <ul id="pagination" data-first="First" data-prev="Previous" data-next="Next" data-last="Last"></ul>
        </div>
      </div>
      <div role="main" class="container body-content hide-when-search">
        
        <div class="sidenav hide-when-search">
          <a class="btn toc-toggle collapse" data-toggle="collapse" href="#sidetoggle" aria-expanded="false" aria-controls="sidetoggle">Show / Hide Table of Contents</a>
          <div class="sidetoggle collapse" id="sidetoggle">
            <div id="sidetoc"></div>
          </div>
        </div>
        <div class="article row grid-right">
          <div class="col-md-10">
            <article class="content wrap" id="_content" data-uid="">
<h1 id="referenced-relationships">Referenced Relationships</h1>

<p>referenced relationships require a bit of special handling. a <strong>one-to-one</strong> relationship is defined using the <code>One&lt;T&gt;</code> class and <strong>one-to-many</strong> as well as <strong>many-to-many</strong> relationships are defined using the <code>Many&lt;T&gt;</code> class and you have to initialize the <code>Many&lt;T&gt;</code> child properties in the constructor of the parent entity as shown below.</p>
<pre><code class="lang-csharp">public class Book : Entity
{
    public One&lt;Author&gt; MainAuthor { get; set; }
    
    public Many&lt;Author&gt; CoAuthors { get; set; }
    
    [OwnerSide] 
    public Many&lt;Genre&gt; Genres { get; set; }

    public Book()
    {
        this.InitOneToMany(() =&gt; CoAuthors);
        this.InitManyToMany(() =&gt; Genres, genre =&gt; genre.Books);
    }
}

public class Genre : Entity
{
    [InverseSide] 
    public Many&lt;Book&gt; Books { get; set; }

    public Genre()
    {
        this.InitManyToMany(() =&gt; Books, book =&gt; book.Genres);
    }
}
</code></pre>
<p>notice the parameters of the <code>InitOneToMany</code> and <code>InitManyToMany</code> methods above. the first method only takes one parameter which is just a lambda pointing to the property you want to initialize.</p>
<p>the next method takes 2 parameters. first is the property to initialize. second is the property of the other side of the relationship.</p>
<p>also note that you specify which side of the relationship a property is using the attributes <code>[OwnerSide]</code> or <code>[InverseSide]</code> for defining many-to-many relationships.</p>
<h2 id="one-to-one">One-to-one</h2>
<p>a reference can be assigned in any of the following three ways:</p>
<pre><code class="lang-csharp">book.MainAuthor = author.ToReference(); //call ToReference on a child
book.MainAuthor = author;               //assign a child instance
book.MainAuthor = &quot;AuthorID&quot;;           //assign just the ID value of a child

await book.SaveAsync();                 //call save on parent to store
</code></pre>
<h3 id="reference-removal">Reference removal</h3>
<pre><code class="lang-csharp">book.MainAuthor = null;
await book.SaveAsync();
</code></pre>
<p>the original <code>author</code> in the <code>Authors</code> collection is unaffected.</p>
<h3 id="entity-deletion">Entity deletion</h3>
<p>if you delete an entity that is referenced as above, all references pointing to that entity would then be invalid. as such, <code>book.MainAuthor.ToEntityAsync()</code> will then return <code>null</code>. the <code>.ToEntityAsync()</code> method is described below.</p>
<p>for example:</p>
<pre><code>book A has 1:1 relationship with author A
book B has 1:1 relationship with author A
book C has 1:1 relationship with author A

now, if you delete author A, the results would be the following:

await bookA.MainAuthor.ToEntityAsync() //returns null
await bookB.MainAuthor.ToEntityAsync() //returns null
await bookC.MainAuthor.ToEntityAsync() //returns null
</code></pre>
<h2 id="one-to-many--many-to-many">One-to-many &amp; many-to-many</h2>
<pre><code class="lang-csharp">await book.Authors.AddAsync(author); //one-to-many
await book.Genres.AddAsync(genre); //many-to-many
</code></pre>
<p>there's no need to call <code>book.SaveAsync()</code> again because references are automatically saved using special join collections. you can read more about them in the <a href="Schema-Changes.html#reference-collections">Schema Changes</a> section.</p>
<p>however, do note that both the parent entity (book) and child (author/genre) being added has to have been previously saved so that they have their <code>ID</code> values populated. otherwise, you'd get an exception instructing you to save them both before calling <code>AddAsync()</code>.</p>
<p>alternatively when you don't have access to the parent entity and you only have the parent <code>ID</code> value, you can use the following to access the relationship:</p>
<pre><code class="lang-csharp">await DB.Entity&lt;Book&gt;(&quot;BookID&quot;).Authors.AddAsync(author);
</code></pre>
<p>there are other <em><a class="xref" href="../api/MongoDB.Entities.Many-1.html#methods">overloads</a></em> for adding relationships with multiple entities or just the string IDs.</p>
<blockquote>
<p><a href="https://gist.github.com/dj-nitehawk/9971a57062f32fac8e7597a889d47714">click here</a> to see a full example of a referenced one-to-many relationship.</p>
</blockquote>
<h3 id="reference-removal-1">Reference removal</h3>
<pre><code class="lang-csharp">await book.Authors.RemoveAsync(author);
await book.Genres.RemoveAsync(genre);
</code></pre>
<p>the original <code>author</code> in the <code>Authors</code> collection is unaffected. also the <code>genre</code> entity in the <code>Genres</code> collection is unaffected. only the relationship between entities are deleted.</p>
<p>there are other <em><a class="xref" href="../api/MongoDB.Entities.Many-1.html#MongoDB_Entities_Many_1_RemoveAsync__0_MongoDB_Driver_IClientSessionHandle_System_Threading_CancellationToken_">overloads</a></em> for removing relationships with multiple entities or just the string IDs.</p>
<h3 id="entity-deletion-1">Entity deletion</h3>
<p>when you delete an entity that's in a <code>one-to-many</code> or <code>many-to-many</code> relationship, all the references (join records) for the relationship in concern are automatically deleted from the join collections.</p>
<p>for example:</p>
<pre><code>| author A has 3 referenced books:
|-- book A
|-- book B
|-- book C

| author B has 3 referenced book:
|-- book A
|-- book B
|-- book C

now, if you delete book B, the children of authors A and B would look like this:

| author A:
|-- book A
|-- book C

| author B:
|-- book A
|-- book C
</code></pre>
<h1 id="toentityasync-shortcut">ToEntityAsync() shortcut</h1>
<p>a reference can be turned back in to an entity with the <code>ToEntityAsync()</code> method.</p>
<pre><code class="lang-csharp">var author = await book.MainAuthor.ToEntityAsync();
</code></pre>
<p>you can also project the properties you need instead of getting back the complete entity like so:</p>
<pre><code class="lang-csharp">var author = await book.MainAuthor
                       .ToEntityAsync(a =&gt; new Author
                        {
                          Name = a.Name,
                          Age = a.Age
                        });
</code></pre>
<h1 id="transaction-support">Transaction support</h1>
<p>adding and removing related entities require passing in the session when used within a transaction. see <a href="Transactions.html#relationship-manipulation">here</a> for an example.</p>
</article>
          </div>
          
          <div class="hidden-sm col-md-2" role="complementary">
            <div class="sideaffix">
              <div class="contribution">
                <ul class="nav">
                </ul>
              </div>
              <nav class="bs-docs-sidebar hidden-print hidden-xs hidden-sm affix" id="affix">
                <h5>In This Article</h5>
                <div></div>
              </nav>
            </div>
          </div>
        </div>
      </div>
      
      <footer>
        <div class="grad-bottom"></div>
        <div class="footer">
          <div class="container">
            <span class="pull-right">
              <a href="#top">Back to top</a>
            </span>
            Developed by <a href='https://github.com/dj-nitehawk'>Đĵ ΝιΓΞΗΛψΚ</a> and <a href='https://github.com/dj-nitehawk/MongoDB.Entities/graphs/contributors'>contributors</a> / Licensed under <a href='https://github.com/dj-nitehawk/MongoDB.Entities/blob/master/LICENSE'>MIT</a> / Website generated by <a href='https://dotnet.github.io/docfx/'>DocFX</a>
            
          </div>
        </div>
      </footer>
    </div>
    
    <script type="text/javascript" src="../styles/docfx.vendor.js"></script>
    <script type="text/javascript" src="../styles/docfx.js"></script>
    <script type="text/javascript" src="../styles/main.js"></script>
  </body>
</html>
